package io.xxx.xbutler.event.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.xxx.xbutler.data.RobotApplyMapper;
import io.xxx.xbutler.data.RobotMapper;
import io.xxx.xbutler.domain.Robot;
import io.xxx.xbutler.domain.RobotApply;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 处理门店的机器人申请单，分配机器人
 */
@Slf4j
@Component
public class RobotApplyAssignJob extends QuartzJobBean {

    @Resource
    private RobotMapper robotMapper;

    @Resource
    private RobotApplyMapper robotApplyMapper;

    @Override
    protected void executeInternal(@Nonnull JobExecutionContext context) {
        LocalDateTime now = LocalDateTime.now();
        List<RobotApply> applies = getNotApproveRobotApplies();
        List<Robot> robots = getValidRobots();

        int index = 0;
        for (Robot robot : robots) {
            int todayCanJoinNum = robot.getTodayJoinNum() - robot.getTodayJoinedNum();

            for (int i = index; i < index + todayCanJoinNum; i++) {
                RobotApply apply = applies.get(i);
                apply.setRobotId(robot.getId())
                        .setRobotSerialNo(robot.getSerialNo())
                        .setAssigned(true)
                        .setUpdatedTime(now);
                robotApplyMapper.updateById(apply);
            }

            index += todayCanJoinNum;
        }
    }

    private List<RobotApply> getNotApproveRobotApplies() {
        LambdaQueryWrapper<RobotApply> wrapper = new LambdaQueryWrapper<RobotApply>()
                .isNull(RobotApply::getRobotId);
        return robotApplyMapper.selectList(wrapper);
    }

    private List<Robot> getValidRobots() {
        LambdaQueryWrapper<Robot> wrapper = new LambdaQueryWrapper<Robot>()
                .select(Robot::getId, Robot::getSerialNo)
                .eq(Robot::getLimited, false);
        return robotMapper.selectList(wrapper);
    }
}
